package com.aaa.salesservice.controller;

import com.aaa.common.entity.Order;
import com.aaa.salesservice.entity.TbNews;
import com.aaa.salesservice.service.TbNewsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (TbNews)表控制层
 *
 * @author YuXin
 * @since 2020-11-05 14:53:50
 */
@RestController
@RequestMapping("tbNews")
public class TbNewsController {
    /**
     * 服务对象
     */
    @Resource
    private TbNewsService tbNewsService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("selectOne")
    public Map selectOne(Integer id) {
        return this.tbNewsService.queryById(id);
    }

    /**
     * selectAllNews  测试熔断
     */
    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
            }
            , fallbackMethod = "selectAllNewsFallBack" //回退方法
    )
    @RequestMapping("selectAllNews")
    public Map selectAllNews() {
        Map map = new HashMap();
        List<TbNews> tbNewsList = this.tbNewsService.selectAllNews();
        List<Order> orderList = restTemplate.getForObject("http://orderService/order/selectAll", List.class);
        map.put("tbNewsList", tbNewsList);
        map.put("orderList", orderList);
        return map;
    }

    private Map selectAllNewsFallBack() {
        Map map = new HashMap();
        List<TbNews> tbNewsList = this.tbNewsService.selectAllNews();
        map.put("tbNewsList", tbNewsList);
        map.put("错误信息", "ribbon-hystrix服务器报错，这是熔断的测试备用方法");
        return map;
    }


    /**
     * 测试控制层的熔断
     */
    //HystrixCommand进行熔断控制 HystrixCommandProperties
    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
            }
            , fallbackMethod = "myFallBack" //回退方法
    )
    @GetMapping("selectTest")
    public String selectTest() {
        System.out.println(10 / 0);
        return "正常模式";
    }

    public String myFallBack() {
        return "熔断模式";
    }
}